<?php
/*
 * @Created by: wangchengcheng
 * @Author: wangchengcheng
 * @Date: 2020-01-09 16:38:20
 * @LastEditors  : wangchengcheng
 * @LastEditTime : 2020-01-13 10:14:47
 */

namespace App\Http\Controllers\Home;


use Agent;
use App;
use Cache;
use Str;
use App\Models\Article;
use App\Models\Category;
use App\Models\Note;
use App\Models\SocialiteUser;
use App\Models\Tag;
use App\Http\Requests\Comment\Store;
use App\Http\Controllers\Controller;
use App\Models\Comment;
use Illuminate\Http\Request;

class IndexController extends Controller
{
    /**
     * 首页
     * 
     * @return Response
     */
    public function index()
    {
        //获取文章列表数据
        $articles = Article::select(
                'id', 'category_id', 'title',
                'slug', 'author', 'description',
                'cover', 'is_top', 'created_at'
            )
            ->orderBy('created_at', 'desc')
            ->with(['category','tags'])
            ->paginate(10);
        $head = [
            'title'         => config('wblog.head.title'),
            'keywords'      => config('wblog.head.keywords'),
            'description'   => config('wblog.head.description'),
        ];
        $assign = [
            'category_id'   => 'indx',
            'articles'      => $articles,
            'head'          => $head,
            'tagName'       => '',
        ];

        return view('home.index.index', $assign);
    }

    /**
     * 文章详情
     * 
     * @param $id
     * 
     */
    public function article($id, Request $request, Comment $commentModel)
    {
        //获取文章数据
        $article = Article::with(['category', 'tags'])->findOrFail($id);

        //同一个用户访问同一篇文章每天只增加1个访问量,使用 ip+id 作为 key 判别
        $ipAndId = 'articleRequestList' . $request->ip() . ':' . $id;
        if(!Cache::has($ipAndId)){
            cache([$ipAndId => ''], 1440);
            //文章点击量+1
            $article->increment('click');
        }

        //获取上一篇
        $prev = Article::select('id', 'title', 'slug')
            ->orderBy('created_at', 'desc')
            ->where('id', '<', $id)
            ->limit(1)
            ->first();

        //获取下一篇
        $next = Article::select('id', 'title', 'slug')
            ->orderBy('created_at', 'asc')
            ->where('id', '>', $id)
            ->limit(1)
            ->first();
        
        //获取评论
        $comment = $commentModel->getDataByArticleId($id);
        $category_id = $article->category->id;

        //Like
        $user = auth()->guard('socialite')->user();

        if($user === null){
            $is_liked = false;
        }else{
            $is_liked = $user->hasLiked($article);
        }
		
        $likes = $article->likers()->get();
        $assign = compact('category_id', 'article', 'prev', 'next',
                    'comment', 'is_liked', 'likes');
                    
        return view('home.index.article', $assign);
    }

    /**
     * 获取分类下的文章
     * 
     * @param $id
     * 
     * @return View
     */
    public function category($id)
    {
        //获取分类数据
        $category = Category::select('id', 'name', 'keywords', 'description')->findOrFail($id);

        //获取分类下的文章
        $articles = $category->articles()
            ->orderBy('created_at', 'desc')
            ->with('tags')
            ->paginate(10);

        //为了和首页共用html,此处手动组合分类数据
        if($articles->isNotEmpty()){
            $articles->setCollection(
                collect(
                    $articles->items()
                )->map(function($v) use ($category){
                    $v->category = $category;

                    return $v;
                })
            );
        }

        $head = [
            'title' => $category->name,
            'keywords' => $category->keywords,
            'description' => $category->description,
        ];
        $assign = [
            'category_id' => $id,
            'articles' => $articles,
            'tagName' => '',
            'title' => $category->name,
            'head' => $head,
        ];

        return view('home.index.index', $assign);
    }

    /**
     * 文章评论
     * 
     * @return JsonResponse
     */
    public function comment(Store $request, Comment $commentModel, SocialiteUser $socialiteUserModel)
    {
        //获取用户Id
        $userId = auth()->guard('socialite')->user()->id;
        //如果用户输入邮箱,则将邮箱记录入socialite_user表中
        $email = $request->input('email', '');
        if(filter_var($email, FILTER_VALIDATE_EMAIL) !== false){
            //修改邮箱
            SocialiteUser::where('id', $userId)->update([
                'email' => $email,
            ]);
        }

        //存储评论
        $comment = Comment::create($request->only('article_id', 'content', 'pid') + [
            'socialite_user_id' => $userId,
            'type'              => 1,
            'is_audited'        => Str::isTrue(config('wblog.comment_audit')) ? 0 : 1,
        ]);

        return response()->json(['id' => $comment->id]);
    }

    /**
     * 获取标签下的文章
     * 
     * @param $id
     */
    public function tag($id)
    {
        //获取标签 以及关键字
        $tag = Tag::select('id', 'name', 'keywords', 'description')->findOrFail($id);

        //TODO 不取mardown 和 html字段
        //获取标签下的文章
        $articles = $tag->articles()
            ->orderBy('created_at', 'desc')
            ->with(['category', 'tags'])
            ->paginate(10);
        $head = [
            'title'         => $tag->name,
            'keywords'      => $tag->keywords,
            'description'   => $tag->description,
        ];
        $assign = [
            'category_id'   => 'index',
            'articles'      => $articles,
            'tagName'       => $tag->name,
            'title'         => $tag->name,
            'head'          => $head,
        ];

        return view('home.index.index', $assign);
    }

    /**
     * 随言碎语
     * 
     * @return mixed
     */
    public function note()
    {
        $notes = Note::orderBy('created_at', 'desc')->get();
        $assign = [
            'category_id'   => 'note',
            'notes'         => $notes,
            'title'         => '随言碎语',
        ];

        return view('home.index.note', $assign);
    }

    /**
     * 开源项目
     * 
     * @return mixed
     */
    public function git()
    {
        $assign = [
            'category_id'   => 'git',
            'title'         => '开源项目',
        ];

        return view('home.index.git', $assign);
    }

    /**
     * 检测是否登录
     */
    public function checkLogin()
    {
        return response()->json([
            'status' => (int) auth()->guard('socialite')->check(),
        ]);
    }

    /**
     * 搜索文章
     * 
     * @return view
     */
    public function search(Request $request, Article $articleModel)
    {
        //禁止蜘蛛抓取搜索页面
        if(Agent::isRobot()){
            abort(404);
        }

        $wd = clean($request->input('wd'));
        $id = $articleModel->searchArticleGetId($wd);

        //获取文章列表数据
        $articles = Article::select(
                'id', 'category_id', 'title',
                'author', 'description', 'cover',
                'is_top', 'created_at' 
            )
            ->whereIn('id', $id)
            ->orderBy('created_at', 'desc')
            ->with(['category', 'tags'])
            ->paginate(10);
        $head = [
            'title'         => $wd,
            'keywords'      => '',
            'description'   => '',
        ];
        $assign = [
            'category_id'   => 'index',
            'articles'      => $articles,
            'tagName'       => '',
            'title'         => $wd,
            'head'          => $head,
        ];

        //增加 X-Rbots-Tag 用于禁止搜索引擎抓取搜索结果页面,防止利用搜索结果页生成恶意广告
        return response()->view('home.index.index', $assign)
            ->header('X-Robots-Tag', 'noindex');
    }

    /**
     * feed
     * 
     * @return View
     */
    public function feed()
    {
        //获取文章
        $article = Article::select('id', 'author', 'title', 'description', 'html', 'created_at')
            ->latest()
            ->get();

        $feed               = App::make('feed');
        $feed->titlte       = config('app.name');
        $feed->description  = config('wblog.head.description');
        $feed->logo         = asset('uploads/avatar/1.jpg');
        $feed->link         = url('feed');
        $feed->setDateFormat('carbon');
        $feed->pubdate      = $article->first()->created_at;
        $feed->lang         = config('app.locate');
        $feed->ctype        = 'application/xml';

        foreach($article as $v){
            $feed->add($v->title, $v->author, url('article', $v->id), $v->created_at, $v->description);
        }

        return $feed->render('atom');
    }
}
